package server;

import pojo.PortAndServlet;
import util.CommonUtil;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat主类
 */
public class Bootstrap {
    /**
     * Minicat启动，需要初始化展开的一些操作
     * 封装res,rep对象，要返回html静态资源文件
     */
    public void start() throws Exception {
        PortAndServlet portAndServlet = CommonUtil.loadServerConf();
        Integer port = portAndServlet.getPort();
        Map<String, HttpServlet> servletMap = portAndServlet.getServletMap();
        //加载解析server.xml文件
        ServerSocket serverSocket = new ServerSocket(port);//监听端口
        System.out.println("=========> Minicat start on port: "+port);
        //使用线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        while (true){
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            threadPoolExecutor.execute(requestProcessor);
        }
    }



    /**
     * 主程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
